<template>
  <div class="editUser">
    <el-dialog :visible.sync="centerDialogVisible"
               :close-on-click-modal="clickModalHide"
               :before-close="closeDialog" width="390px"
               :title="type=='add'?'添加人员':'修改人员'">
      <el-form :model="editData" size="mini" status-icon :rules="rules" ref="editData" label-width="100px"
               class="demo-ruleForm">
        <!--<el-form-item label="工段" prop="gwId">-->
          <!--<el-select v-model="editData.gwId" filterable placeholder="请选择">-->
            <!--<el-option-->
              <!--v-for="item in gongquList"-->
              <!--:key="item.id"-->
              <!--:label="item.gqName"-->
              <!--:value="item.id">-->
            <!--</el-option>-->
          <!--</el-select>-->
        <!--</el-form-item>-->
        <el-form-item label="部门：" >
          <el-select v-model="editData.deptId" filterable placeholder="请选择" style="width: 75%;">
            <el-option
              v-for="item in deptList"
              :key="item.id"
              :label="item.deptName"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="角色：" prop="roleId">
          <el-select v-model="editData.roleId"  @change="changRole" filterable placeholder="请选择" style="width: 75%;">
            <el-option
              v-for="item in roleList"
              :key="item.id"
              :label="item.roleName"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="工号：" prop="workNum">
          <el-input v-model="editData.workNum" @blur="leaveMouse" :disabled="type == 'edit'" style="width: 75%;"></el-input>
        </el-form-item>
        <el-form-item label="姓名：" prop="userName">
          <el-input v-model="editData.userName" style="width: 75%;"></el-input>
        </el-form-item>

        <el-form-item label="用户名：" prop="userAccount">
          <el-input v-model="editData.userAccount" style="width: 75%;"></el-input>
        </el-form-item>

        <el-form-item label="密码：" prop="password" v-if="type =='add'">
          <el-input v-model="editData.password" type="password" style="width: 75%;"></el-input>
        </el-form-item>
        <el-form-item label="确认密码：" prop="checkPass" v-if="type =='add'">
          <el-input v-model="editData.checkPass"  type="password" style="width: 75%;"></el-input>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="submitForm('editData')">提交</el-button>
          <el-button @click="resetForm('editData')">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>
<script>
  export default {
    name: 'editLogin',
    props: ['dataDetail', 'type','existLogin'],
    data() {
      var notEmpty = (rule, value, callback) => {
        if (!value) {
          return callback(new Error('不能为空'));
        } else {
          callback();
        }
      };
      var validateLogin= (rule, value, callback) => {
        let logins = [];
        if(this.existLogin && this.existLogin.length > 0){
          for(let data of this.existLogin){
            logins.push(data.userAccount);
          }
        }
        if (value === '') {
          callback(new Error('请输入账号'));
        } else if (logins.includes(this.editData.userAccount)) {
          callback(new Error('账号已存在!'));
        } else {
          callback();
        }
      };

      var validateWorkNum= (rule, value, callback) => {
        let workNums = [];
        if(this.existLogin && this.existLogin.length > 0){
          for(let data of this.existLogin){
            workNums.push(data.workNum);
          }
        }
        if (value === '') {
          callback(new Error('请输入工号'));
        } else if (workNums.includes(this.editData.workNum)) {
          callback(new Error('工号已存在!'));
        } else {
          callback();
        }
      };

      var validatePass2 = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请再次输入密码'));
        } else if (value !== this.editData.password) {
          callback(new Error('两次输入密码不一致!'));
        } else {
          callback();
        }
      };
      return {
        centerDialogVisible: false,
        clickModalHide: false,
        gongquList: [],
        deptList: [],
        roleList: [],
        editData: {
          workNum: "",
          userName: "",
          deptId: "",
          roleId: "",
          userAccount: "",
          accountType: "",
          password: "",
          checkPass:"",
        },
        rules: {
          workNum: [
            {validator: validateWorkNum, trigger: 'blur'}
          ],
          userName: [
            {validator: notEmpty, trigger: 'blur'}
          ],
          deptId: [
            {validator: notEmpty, trigger: 'blur'}
          ],
          roleId: [
            {validator: notEmpty, trigger: 'blur'}
          ],
          userAccount: [
            {validator: validateLogin, trigger: 'blur'}
          ],
          password: [
            {validator: notEmpty, trigger: 'blur'}
          ],
          checkPass: [
            { validator: validatePass2, trigger: 'blur' }
          ]

        },
        count: 0,
      }
    },


    mounted() {
      // this.getGongQu();
      this.getDeptList();
      this.getRole();
    },

    methods: {

      leaveMouse(){
        const str = this.editData.workNum.replace(/\s*/g,"");
        this.editData.workNum = str;
      },

      getAllRole() {
        let self = this;
        self.$http({
          url: "/autoMonitor/user/queryAllRole",
          method: "post",
        }).then(resp => {
          if (resp.success) {
            self.roleList = resp.result;
          }
        });
      },

      operateLogin() {
        let self = this;
        let param = self.getParam();
        let url = this.type == 'add' ? "/autoMonitor/user/addUserDetail" : "/autoMonitor/user/updateUserDetail";
        if (this.count == 0) {
          self.$http({
            url: url,
            method: "post",
            data: JSON.stringify(param),
            dataType: 'json',
            contentType: "application/json",
          }).then(resp => {
            if (resp.success) {
              self.$eventBus.$emit("updateLogin");
              self.$notify({
                title: '提示',
                message: "操作成功！",
                type: 'success'
              });
              self.resetForm('editData');
              return
            }
            self.$notify({
              title: '提示',
              message: resp.message,
              type: 'error'
            });
            this.count--;
          });
          this.count++;
        }
      },

      getParam() {
        let param = {};
        param.id = this.editData.id?this.editData.id:"";
        param.userAccount = this.editData.userAccount;
        if(this.type == 'add'){
          param.password = this.editData.password;
        }
        param.accountType = this.editData.accountType;
        let workNum = this.editData.workNum.replace(/\s+/g,"");
        param.userDetail = {
          id: this.editData.userId?this.editData.userId:"",
          userName: this.editData.userName,
          workNum: workNum,
          roleId:this.editData.roleId,
          deptId:this.editData.deptId,
        };
        return param;
      },
      //关闭弹窗
      closeDialog() {
        this.$refs['editData'].clearValidate();
        this.centerDialogVisible = false;
      },

      submitForm(formName) {
        let self = this;
        this.$refs[formName].validate((valid) => {
          if (valid) {
            self.operateLogin();
          } else {
            return false;
          }
        });
      },
      resetForm(formName) {
        this.$refs[formName].clearValidate();
        this.closeDialog();
      },


      getDeptList() {
        let self = this;
        self.$http({
          url: "/autoMonitor/dept/queryDeptList",
          method: "post",
          params: {convertChild: false}
        }).then(resp => {
          if (resp.success) {
            self.deptList = resp.result;
          }
        });
      },
      getGongQu() {
        let self = this;
        self.$http({
          url: "/autoMonitor/gd/queryGongDuanList",
          method: "post",
        }).then(resp => {
          if (resp.success) {
            self.gongquList = resp.result;
          }
        });
      },

      changRole() {
        let roleId = this.editData.roleId;
        for (let role of this.roleList) {
          if (role.id == roleId) {
            this.editData.accountType = role.roleType;
          }
        }
        if(this.editData.accountType == '1'){

        }
      },

      getRole() {
        let self = this;
        self.$http({
          url: "/autoMonitor/permission/queryAllRole",
          method: "post",
        }).then(resp => {
          if (resp.success) {
            self.roleList = resp.result;
          }
        });
      },

    },
    watch: {
      dataDetail(val) {
        this.count = 0;
        this.centerDialogVisible = true;
        for (let key in this.editData) {
          if (!val.hasOwnProperty(key)) {
            val[key] = "";
          }
        }
        this.editData = val;
      }
    }
  }
</script>
<style scoped>
  .editUser .el-dialog__body {
    padding: 0px 20px;
  }

  .editUser .el-form-item {
    margin-bottom: 18px;
  }

</style>
